//
//  EnergyBenchmarkingView.m
//  cocoapodText
//
//  Created by apple on 16/9/10.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "ShiPei.h"
#import <Foundation/Foundation.h>
#import "EnergyBenchmarkingView.h"

@interface EnergyBenchmarkingView()<FSMyUIDatePickerDelegate,UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)NSMutableArray *energyTypes;
@property(nonatomic,strong)NSMutableArray *conditionInfos;
@property(nonatomic,strong)NSMutableArray *queryDataInfos;
@end

@implementation EnergyBenchmarkingView

/**
 *  初始化视图属性
 *
 *  @param frame 视图frame
 *
 *  @return self
 */
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //定制View
        self.backgroundColor = [UIColor clearColor];
        self.userInteractionEnabled = YES; //设置为NO后，不再响应touch方法
        self.multipleTouchEnabled = YES;
        //控制子视图不能超出父视图的范围
        self.clipsToBounds = YES;
        //添加子视图
        [self subView];
    }
    return self;
}

//子视图懒加载
-(void)subView{
    //内容栏
    _AllBackView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, [ShiPei CGFloatMakeScale:TabChildContentW+10], kScreenH-CommonBarH-kStatusH-[ShiPei CGFloatMakeScale:FSCommonBottomH])];
    [self addSubview:_AllBackView];
    
    _pickerOverlay=[[UIView alloc]initWithFrame:CGRectMake(0, 0, [ShiPei CGFloatMakeScale:TabChildContentW+10], kScreenH-CommonBarH-kStatusH)];
    [_pickerOverlay setBackgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.17]];
    UITapGestureRecognizer *gestureRecognizer;
    gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                action:@selector(overlaycancel)];
    [_pickerOverlay addGestureRecognizer:gestureRecognizer];
    
    [self initEnergyAnalysisMenu];
    [self initEnergyQueryMenu];
    [self initShowChartView];
    [self initQueryTableView];
}

-(void)initEnergyAnalysisMenu{
    UIView *EnergyAnalysisMenu=[[UIView alloc]initWithFrame:CGRectMake(0, 0, [ShiPei CGFloatMakeScale:210],  kScreenH-CommonBarH-kStatusH)];
    [_AllBackView addSubview:EnergyAnalysisMenu];
    [EnergyAnalysisMenu setUserInteractionEnabled:YES];
    [EnergyAnalysisMenu setBackgroundColor:[UIColor whiteColor]];
    
    //表格顶部
    UIView *tableTopView=[[UIView alloc]initWithFrame:[ShiPei CGRectMakeScale:10 :15 :185 :35]];
    [EnergyAnalysisMenu addSubview:tableTopView];
    [tableTopView setUserInteractionEnabled:YES];
    [tableTopView setBackgroundColor:FUIColorFromRGB(0x84b6e7)];
    
    UILabel *tableTopLabel=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:17.5 :0 :130 :35]];
    [tableTopView addSubview:tableTopLabel];
    [tableTopLabel setBackgroundColor:[UIColor clearColor]];
    [tableTopLabel setText:@"贵阳市"];
    [tableTopLabel setTextColor:FUIColorFromRGB(0x333333)];
    [tableTopLabel setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:26]]];
    
    UILabel *tableTopAddLabel=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:147.5 :0 :37.5 :35]];
    [tableTopView addSubview:tableTopAddLabel];
    [tableTopAddLabel setBackgroundColor:[UIColor clearColor]];
    [tableTopAddLabel setText:@"+"];
    [tableTopAddLabel setTextAlignment:NSTextAlignmentCenter];
    [tableTopAddLabel setTextColor:[UIColor whiteColor]];
    [tableTopAddLabel setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:40]]];
    
    //表格
    _GYMeunTableView=[[UITableView alloc]initWithFrame:CGRectMake([ShiPei CGFloatMakeScale:10], [ShiPei CGFloatMakeScale:50], [ShiPei CGFloatMakeScale:185], kScreenH-CommonBarH-kStatusH-[ShiPei CGFloatMakeScale:FSChangeTrendMenuH+70])];
    [EnergyAnalysisMenu addSubview:_GYMeunTableView];
    [_GYMeunTableView setBackgroundColor:[UIColor clearColor]];
    [_GYMeunTableView setUserInteractionEnabled:YES];
    [_GYMeunTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_GYMeunTableView setDelegate:self];
    [_GYMeunTableView setDataSource:self];
    
}

-(void)initEnergyQueryMenu{
    _rightAllBackView=[[UIView alloc] initWithFrame:CGRectMake([ShiPei CGFloatMakeScale:225], 0, [ShiPei CGFloatMakeScale:630], kScreenH-CommonBarH-kStatusH)];
    [_AllBackView addSubview:_rightAllBackView];
    [_rightAllBackView setUserInteractionEnabled:YES];
    [_rightAllBackView setBackgroundColor:[UIColor clearColor]];
    
    UIView *EnergyQueryMenu=[[UIView alloc]initWithFrame:[ShiPei CGRectMakeScale:0 :15 :630 :40]];
    [_rightAllBackView addSubview:EnergyQueryMenu];
    [EnergyQueryMenu setUserInteractionEnabled:YES];
    [EnergyQueryMenu setBackgroundColor:[UIColor whiteColor]];
    
    UILabel *energyTypeLabel=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:15 :0 :62.5 :40]];
    [EnergyQueryMenu addSubview:energyTypeLabel];
    [energyTypeLabel setTextAlignment:NSTextAlignmentCenter];
    [energyTypeLabel setUserInteractionEnabled:YES];
    [energyTypeLabel setText:@"能源类型"];
    [energyTypeLabel setTextColor:FUIColorFromRGB(0x333333)];
    [energyTypeLabel setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:25]]];
    
    //能源类型选择
    UILabel *energyTypeMenu=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:77.5 :7.5 :60 :25]];
    [EnergyQueryMenu addSubview:energyTypeMenu];
    [energyTypeMenu setTextAlignment:NSTextAlignmentCenter];
    [energyTypeMenu setBackgroundColor:FUIColorFromRGB(0xe1e1e1)];
    [energyTypeMenu.layer setMasksToBounds:YES];
    [energyTypeMenu.layer setCornerRadius:10];
    [energyTypeMenu setUserInteractionEnabled:YES];
    [energyTypeMenu setText:@""];
    [energyTypeMenu setTextColor:FUIColorFromRGB(0x1b75cc)];
    [energyTypeMenu setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:25]]];
    
    UITapGestureRecognizer *singleTap0 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonpress0:)];
    [energyTypeMenu addGestureRecognizer:singleTap0];
    self.energyTypeMenu=energyTypeMenu;
    
    
    UILabel *jiangeLabel=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:145 :0 :65 :40]];
    [EnergyQueryMenu addSubview:jiangeLabel];
    [jiangeLabel setTextAlignment:NSTextAlignmentCenter];
    [jiangeLabel setUserInteractionEnabled:YES];
    [jiangeLabel setText:@"对比方式"];
    [jiangeLabel setTextColor:FUIColorFromRGB(0x333333)];
    [jiangeLabel setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:25]]];
    
    //对比方式
    UILabel *duibiTypeMenu=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:210 :7.5 :75 :25]];
    [EnergyQueryMenu addSubview:duibiTypeMenu];
    [duibiTypeMenu setTextAlignment:NSTextAlignmentCenter];
    [duibiTypeMenu setUserInteractionEnabled:YES];
    [duibiTypeMenu setBackgroundColor:FUIColorFromRGB(0xe1e1e1)];
    [duibiTypeMenu.layer setMasksToBounds:YES];
    [duibiTypeMenu.layer setCornerRadius:10];
    [duibiTypeMenu setUserInteractionEnabled:YES];
    [duibiTypeMenu setText:@""];
    [duibiTypeMenu setTextColor:FUIColorFromRGB(0x1b75cc)];
    [duibiTypeMenu setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:25]]];
    
    UITapGestureRecognizer *singleTap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonpress1:)];
    [duibiTypeMenu addGestureRecognizer:singleTap3];
    self.duibiTypeMenu=duibiTypeMenu;
    
    UILabel *showTypeLabel=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:290 :0 :60 :40]];
    [EnergyQueryMenu addSubview:showTypeLabel];
    [showTypeLabel setTextAlignment:NSTextAlignmentCenter];
    [showTypeLabel setUserInteractionEnabled:YES];
    [showTypeLabel setText:@"显示类型"];
    [showTypeLabel setTextColor:FUIColorFromRGB(0x333333)];
    [showTypeLabel setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:25]]];
    
    //显示类型
    UILabel *showTypeMenu=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:350 :7.5 :40 :25]];
    [EnergyQueryMenu addSubview:showTypeMenu];
    [showTypeMenu setTextAlignment:NSTextAlignmentCenter];
    [showTypeMenu setUserInteractionEnabled:YES];
    [showTypeMenu setBackgroundColor:FUIColorFromRGB(0xe1e1e1)];
    [showTypeMenu.layer setMasksToBounds:YES];
    [showTypeMenu.layer setCornerRadius:10];
    [showTypeMenu setUserInteractionEnabled:YES];
    [showTypeMenu setText:@""];
    [showTypeMenu setTextColor:FUIColorFromRGB(0x1b75cc)];
    [showTypeMenu setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:25]]];
    
    UITapGestureRecognizer *singleTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonpress2:)];
    [showTypeMenu addGestureRecognizer:singleTap1];
    self.showTypeMenu=showTypeMenu;
    
    UILabel *startEndTimeLabel=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:390 :0 :70 :40]];
    [EnergyQueryMenu addSubview:startEndTimeLabel];
    [startEndTimeLabel setTextAlignment:NSTextAlignmentCenter];
    [startEndTimeLabel setUserInteractionEnabled:YES];
    [startEndTimeLabel setText:@"时间"];
    [startEndTimeLabel setTextColor:FUIColorFromRGB(0x333333)];
    [startEndTimeLabel setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:25]]];
    
    //开始时间
    UILabel *startTimeMenu=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:460 :7.5 :80 :25]];
    [EnergyQueryMenu addSubview:startTimeMenu];
    [startTimeMenu setTextAlignment:NSTextAlignmentCenter];
    [startTimeMenu setUserInteractionEnabled:YES];
    [startTimeMenu setBackgroundColor:FUIColorFromRGB(0xe1e1e1)];
    [startTimeMenu.layer setMasksToBounds:YES];
    [startTimeMenu.layer setCornerRadius:10];
    [startTimeMenu setUserInteractionEnabled:YES];
    [startTimeMenu setText:@""];
    [startTimeMenu setTextColor:FUIColorFromRGB(0x1b75cc)];
    [startTimeMenu setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:25]]];
    
    UITapGestureRecognizer *singleTap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(startTimeClick:)];
    [startTimeMenu addGestureRecognizer:singleTap2];
    self.startTimeMenu=startTimeMenu;
    
    
    UIButton *queryButton=[[UIButton alloc]initWithFrame:[ShiPei CGRectMakeScale:557.5 :15/2 :50 :25]];
    [EnergyQueryMenu addSubview:queryButton];
    [queryButton setBackgroundImage:[CommonTool createImageWithColor:FUIColorFromRGB(0x3388cb) Frame:[ShiPei CGRectMakeScale:0 :0 :50 :25]] forState:UIControlStateNormal];
    [queryButton setBackgroundImage:[CommonTool createImageWithColor:FUIColorFromRGB(0x639ed7)  Frame:[ShiPei CGRectMakeScale:0 :0 :50 :25]] forState:UIControlStateHighlighted];
    [queryButton.layer setMasksToBounds:YES];
    [queryButton.layer setCornerRadius:5];
    [queryButton setTitle:@"查询" forState:UIControlStateNormal];
    [queryButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [queryButton.titleLabel setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:26]]];
    [queryButton addTarget:self action:@selector(onClickQuery) forControlEvents:UIControlEventTouchUpInside];
    [self initPickerView];
}

-(void)initPickerView{
    _is_picker_show=NO;
    _datePicker=[[MyUIDatePicker alloc]initWithFrame:CGRectMake(0, kScreenH-CommonBarH-kStatusH-[ShiPei CGFloatMakeScale:250], [ShiPei CGFloatMakeScale:860], [ShiPei CGFloatMakeScale:250])];
    [_datePicker setDelegate:self];
    [_pickerOverlay addSubview:_datePicker];
}



-(void)initShowChartView{
    _chartAndQueryTableBack=[[UIScrollView alloc]initWithFrame:CGRectMake(0, [ShiPei CGFloatMakeScale:70], [ShiPei CGFloatMakeScale:630], kScreenH-CommonBarH-kStatusH-[ShiPei CGFloatMakeScale:80])];
    [_rightAllBackView addSubview:_chartAndQueryTableBack];
    [_chartAndQueryTableBack setUserInteractionEnabled:YES];
    _chartAndQueryTableBack.showsVerticalScrollIndicator = FALSE;
    _chartAndQueryTableBack.showsHorizontalScrollIndicator = FALSE;
    _chartAndQueryTableBack.bounces = NO;
    [_chartAndQueryTableBack setBackgroundColor:[UIColor clearColor]];
    
    UIView *showChartBack=[[UIView alloc]initWithFrame:[ShiPei CGRectMakeScale:0 :0 :630 :325]];
    [_chartAndQueryTableBack addSubview:showChartBack];
    [showChartBack setUserInteractionEnabled:YES];
    [showChartBack setBackgroundColor:[UIColor whiteColor]];
    
    self.chartTitle=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:20 :0 :580 :25]];
    [self.chartTitle setTextAlignment:NSTextAlignmentCenter];
    [self.chartTitle setText:@""];
    [self.chartTitle setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:20]]];
    [self.chartTitle setTextColor:FUIColorFromRGB(0x333333)];
    [self.chartTitle setBackgroundColor:[UIColor clearColor]];
    [showChartBack addSubview:self.chartTitle];
    
    _energyBarChart=[[BarChartView alloc] initWithFrame:[ShiPei CGRectMakeScale:20 :25 :580 :280]];
    _energyBarChart.backgroundColor = [UIColor whiteColor];
    [showChartBack addSubview:_energyBarChart];
    [self initBarChartStyleAndData];
    
}

-(void)initQueryTableView{
    _queryTableBack=[[UIScrollView alloc]initWithFrame:CGRectMake(0, [ShiPei CGFloatMakeScale:340], [ShiPei CGFloatMakeScale:630], kScreenH-CommonBarH-kStatusH-[ShiPei CGFloatMakeScale:420])];
    [_chartAndQueryTableBack addSubview:_queryTableBack];
    [_queryTableBack setUserInteractionEnabled:YES];
    _queryTableBack.showsVerticalScrollIndicator = FALSE;
    _queryTableBack.showsHorizontalScrollIndicator = FALSE;
    _queryTableBack.bounces = NO;
    [_queryTableBack setBackgroundColor:[UIColor whiteColor]];
    
    //表格顶部
    _queryTabletopView=[[UIView alloc]initWithFrame:[ShiPei CGRectMakeScale:0 :0 :630 :35]];
    [_queryTableBack addSubview:_queryTabletopView];
    [_queryTabletopView setBackgroundColor:FUIColorFromRGB(0x84b6e7)];
    duibiaoDataTableCellview *tableCellView=[[duibiaoDataTableCellview alloc] initWithFrame:[ShiPei CGRectMakeScale:0 :0 :TabChildContentW :35]];
    [_queryTabletopView addSubview:tableCellView];
    [tableCellView setBackgroundColor:[UIColor clearColor]];
    self.tableCellView=tableCellView;
    
    //表格头部数据组装
    [_tableCellView setName:@"能耗对象"];
    [_tableCellView setKWH:@"总能耗"];
    [_tableCellView setCoal:@"总能耗/人均能耗"];
    [_tableCellView setCarbon:@"标杆值"];
    [_tableCellView setMaxmin:@"最大值~最小值"];
    
    
    _queryTableView=[[UITableView alloc]initWithFrame:
                     CGRectMake(0, [ShiPei CGFloatMakeScale:35], [ShiPei CGFloatMakeScale:630], kScreenH-CommonBarH-kStatusH-[ShiPei CGFloatMakeScale:455])];
    [_queryTableBack addSubview:_queryTableView];
    _queryTableView.scrollEnabled =NO; //设置tableview 不能滚动
    _queryTableView.bounces=NO;//去掉弹簧效果
    [_queryTableView setUserInteractionEnabled:YES];
    [_queryTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_queryTableView setDelegate:self];
    [_queryTableView setDataSource:self];
    [_queryTableView setBackgroundColor:[UIColor clearColor]];
}

-(void)setInitCondition{
    //默认显示类型为日
    _xslxType=@"2";
    [_showTypeMenu setText:@"月"];
    //默认选择贵阳市
    _currentAreaName=@"贵阳市";
    _orgid=@"520100000:4:贵阳市:00";
    //contrastType(对比方式)
    _contrastType=@"2";
    _contrastName=@"单位面积";
    [self.duibiTypeMenu setText:_contrastName];
    //查询时间
    _startTime=[CommonTool getDateTimeDifferenceWithYear:0 Month:-1 Day:0 Rule:@"yyyyMM"];
    [_startTimeMenu setText:_startTime];
}

//能源类型
-(void)setGYMenuEnergyTypeData:(NSArray *)array{
    _energyTypes=[NSMutableArray array];
    for (int i=0; i<[array count]; i++) {
        NSDictionary *temDic=[array objectAtIndex:i];
        [_energyTypes addObject:temDic];
    }
    //默认能源类型
    NSDictionary *temDic=[_energyTypes objectAtIndex:0];
    NSString *name=[CommonTool getStringFromNSDictionary:temDic key:@"name" defaultValue:@""];
    _energyType=[CommonTool getStringFromNSDictionary:temDic key:@"esCode" defaultValue:@""];
    [self.energyTypeMenu setText:name];
    if([_delegate respondsToSelector:@selector(onInitFristChartTableData:esCode:)]){
        [_delegate onInitFristChartTableData:self esCode:_energyType];
    }
}

//根据左侧菜单分类填充单选列表
-(void)setGYMenuTableData:(NSArray *)array{
    _conditionInfos=[NSMutableArray array];
    for (int i=1; i<[array count]; i++) {
        NSDictionary *temDic=[array objectAtIndex:i];
        NSString *name=[CommonTool getStringFromNSDictionary:temDic key:@"name" defaultValue:@""];
        NSString *areaId=[CommonTool getStringFromNSDictionary:temDic key:@"id" defaultValue:@""];
        energyConditionInfo *model;
        NSString *encode=[CommonTool getStringFromNSDictionary:temDic key:@"encode" defaultValue:@""];
        if (i%2==0) {
            model=[energyConditionInfo energyConditionInfoWithCondition:name isOdd:@"0" isSelect:@"0" flagNo:
                   areaId encode:encode];
        }else{
            model=[energyConditionInfo energyConditionInfoWithCondition:name isOdd:@"1"  isSelect:@"0" flagNo:
                   areaId encode:encode];
        }
        [_conditionInfos addObject:model];
    }
    //通知主线程刷新
    dispatch_async(dispatch_get_main_queue(), ^{
        //回调或者说是通知主线程刷新
        [self.GYMeunTableView reloadData];
    });
}

-(void)setEnergyTableWithTitle:(NSString *)title header:(NSDictionary *)tableHeaderObj Data:(NSArray *)tableBodyObj{
//    NSLog(@"tableHeaderObj=%@",tableHeaderObj);
//    NSLog(@"tableBodyObj=%@",tableBodyObj);
    _queryDataInfos=[NSMutableArray array];
    NSMutableArray *models=[NSMutableArray array];
    for (int i=0; i<[tableBodyObj count]; i++) {
        //一条表数据
        //{"maxToMin":"-- ~ --","unitEnergy":"--","benchmarking":"--","serialNumber":1,"energyObject":"办公建筑","totalEnergy":"--"
        // maxToMin:最大值~最小值
        // totalEnergy/unitEnergy:总能耗/单位面积能耗
        // benchmarking:标杆值
        // serialNumber:序号
        // energyObject：能耗对象
        
        
        NSDictionary *temDic=[tableBodyObj objectAtIndex:i];
        NSString *unitEnergy = [CommonTool getStringFromNSDictionary:temDic key:@"unitEnergy" defaultValue:@""];
        NSString *maxToMin = [CommonTool getStringFromNSDictionary:temDic key:@"maxToMin" defaultValue:@""];
        NSString *energyObject = [CommonTool getStringFromNSDictionary:temDic key:@"energyObject" defaultValue:@""];
        NSString *benchmarking = [CommonTool getStringFromNSDictionary:temDic key:@"benchmarking" defaultValue:@"0"];
        NSString *totalEnergy = [CommonTool getStringFromNSDictionary:temDic key:@"totalEnergy" defaultValue:@""];
        //组装数据
        duibiaoDataInfo *model;
        if (i%2==0) {
            model=[duibiaoDataInfo duibiaoDataInfoWithItemName:energyObject itemKWH:totalEnergy itemCoal:unitEnergy itemCarbon:benchmarking isOdd:@"0" itemMaxmin:maxToMin];
        }else{
            model=[duibiaoDataInfo duibiaoDataInfoWithItemName:energyObject itemKWH:totalEnergy itemCoal:unitEnergy itemCarbon:benchmarking isOdd:@"1" itemMaxmin:maxToMin];
        }
        
        [models addObject:model];
    }
    _queryDataInfos=[models copy];
    
    //刷新数据
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // 处理耗时操作的代码块...
        //通知主线程刷新
        dispatch_async(dispatch_get_main_queue(), ^{
            //表格头部数据组装
            [_tableCellView setName:@"能耗对象"];
            [_tableCellView setKWH:@"总能耗"];
            NSString *coal=@"总能耗/";
            coal=[coal stringByAppendingString:_contrastName];
            [_tableCellView setCoal:coal];
            [_tableCellView setCarbon:@"标杆值"];
            [_tableCellView setMaxmin:@"最大值~最小值"];
            //回调或者说是通知主线程刷新
            [_queryTableView reloadData];
        });
    });
}

-(void)buttonpress0:(UITapGestureRecognizer *)recognizer{
    if (_energyTypes!=nil) {
        _currentMenu=@"buttonpress0";
    NSMutableArray *models=[NSMutableArray array];
    for (int i=0; i<[_energyTypes count]; i++) {
        NSDictionary *temDic=[_energyTypes objectAtIndex:i];
        NSString *name=[CommonTool getStringFromNSDictionary:temDic key:@"name" defaultValue:@""];
        NSString *esCode=[CommonTool getStringFromNSDictionary:temDic key:@"esCode" defaultValue:@""];
        if (![name isEqualToString:@""]&&![esCode isEqualToString:@"00"]) {
            KxMenuItem *model;
            model=[KxMenuItem menuItem:name image:nil target:self action:@selector(KxMenuItemClick:)];
            [models addObject:model];
        }
    }
    
    [KxMenu setTitleFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:25]]];
    Color color,color2;
    color.R=0;
    color.G=0;
    color.B=0;
    color2.R=1;
    color2.G=1;
    color2.B=1;
    OptionalConfiguration options;
    options.arrowSize=9;//指示箭头大小
    options.marginXSpacing= 7;  //MenuItem左右边距
    options.marginYSpacing= 9;  //MenuItem上下边距
    options.intervalSpacing= 25;  //MenuItemImage与MenuItemTitle的间距
    options.menuCornerRadius= 6.5;  //菜单圆角半径
    options.maskToBackground= true;  //是否添加覆盖在原View上的半透明遮罩
    options.shadowOfMenu= false;  //是否添加菜单阴影
    options.hasSeperatorLine= true;  //是否设置分割线
    options.seperatorLineHasInsets= false;  //是否在分割线两侧留下Insets
    options.textColor=color;  //menuItem字体颜色
    options.menuBackgroundColor= color2;  //菜单的底色
    [KxMenu showMenuInView:_rightAllBackView fromRect:recognizer.view.frame menuItems:models withOptions:options];
    }
}

-(void)buttonpress1:(UITapGestureRecognizer *)recognizer{
    _currentMenu=@"buttonpress1";
    NSMutableArray *models=[NSMutableArray array];
    //contrastType=对比类型 (2：单位面积 3：人均能耗  4：空调面积)
    //contrastName=单位面积、人均能耗、空调面积
    
    KxMenuItem *model;
    model=[KxMenuItem menuItem:@"单位面积" image:nil target:self action:@selector(KxMenuItemClick:)];
    [models addObject:model];
    
    model=[KxMenuItem menuItem:@"人均能耗" image:nil target:self action:@selector(KxMenuItemClick:)];
    [models addObject:model];
    
    model=[KxMenuItem menuItem:@"空调面积" image:nil target:self action:@selector(KxMenuItemClick:)];
    [models addObject:model];
    
    
    [KxMenu setTitleFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:25]]];
    Color color,color2;
    color.R=0;
    color.G=0;
    color.B=0;
    color2.R=1;
    color2.G=1;
    color2.B=1;
    OptionalConfiguration options;
    options.arrowSize=9;//指示箭头大小
    options.marginXSpacing= 7;  //MenuItem左右边距
    options.marginYSpacing= 9;  //MenuItem上下边距
    options.intervalSpacing= 25;  //MenuItemImage与MenuItemTitle的间距
    options.menuCornerRadius= 6.5;  //菜单圆角半径
    options.maskToBackground= true;  //是否添加覆盖在原View上的半透明遮罩
    options.shadowOfMenu= false;  //是否添加菜单阴影
    options.hasSeperatorLine= true;  //是否设置分割线
    options.seperatorLineHasInsets= false;  //是否在分割线两侧留下Insets
    options.textColor=color;  //menuItem字体颜色
    options.menuBackgroundColor= color2;  //菜单的底色
    [KxMenu showMenuInView:_rightAllBackView fromRect:recognizer.view.frame menuItems:models withOptions:options];
    
}

-(void)buttonpress2:(UITapGestureRecognizer *)recognizer{
    _currentMenu=@"buttonpress2";
    NSMutableArray *models=[NSMutableArray array];
    KxMenuItem *model;
    model=[KxMenuItem menuItem:@"月" image:nil target:self action:@selector(KxMenuItemClick:)];
    [models addObject:model];
    
    model=[KxMenuItem menuItem:@"年" image:nil target:self action:@selector(KxMenuItemClick:)];
    [models addObject:model];
    
    [KxMenu setTitleFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:25]]];
    Color color,color2;
    color.R=0;
    color.G=0;
    color.B=0;
    color2.R=1;
    color2.G=1;
    color2.B=1;
    OptionalConfiguration options;
    options.arrowSize=9;//指示箭头大小
    options.marginXSpacing= 7;  //MenuItem左右边距
    options.marginYSpacing= 9;  //MenuItem上下边距
    options.intervalSpacing= 25;  //MenuItemImage与MenuItemTitle的间距
    options.menuCornerRadius= 6.5;  //菜单圆角半径
    options.maskToBackground= true;  //是否添加覆盖在原View上的半透明遮罩
    options.shadowOfMenu= false;  //是否添加菜单阴影
    options.hasSeperatorLine= true;  //是否设置分割线
    options.seperatorLineHasInsets= false;  //是否在分割线两侧留下Insets
    options.textColor=color;  //menuItem字体颜色
    options.menuBackgroundColor= color2;  //菜单的底色
    [KxMenu showMenuInView:_rightAllBackView fromRect:recognizer.view.frame menuItems:models withOptions:options];
}
-(void)dismissMenu{
    [KxMenu dismissMenu];
}
-(void)KxMenuItemClick:(id)sender{
    KxMenuItem *model=sender;
    if ([_currentMenu isEqualToString:@"buttonpress0"]) {
        for (int i=0; i<[_energyTypes count]; i++) {
            NSDictionary *temDic=[_energyTypes objectAtIndex:i];
            NSString *name=[CommonTool getStringFromNSDictionary:temDic key:@"name" defaultValue:@""];
            if ([model.title isEqualToString:name]) {
                _energyType=[CommonTool getStringFromNSDictionary:temDic key:@"esCode" defaultValue:@""];
                [self.energyTypeMenu setText:name];
                [self onClickQuery];
            }
        }
    }else if ([_currentMenu isEqualToString:@"buttonpress1"]) {
        //contrastType=对比类型 (2：单位面积 3：人均能耗  4：空调面积)
        //contrastName=单位面积、人均能耗、空调面积
        if ([model.title isEqualToString:@"单位面积"]) {
            _contrastName=@"单位面积";
            _contrastType=@"2";
        }else if ([model.title isEqualToString:@"人均能耗"]) {
            _contrastName=@"人均能耗";
            _contrastType=@"3";
        }else if ([model.title isEqualToString:@"空调面积"]) {
            _contrastName=@"空调面积";
            _contrastType=@"4";
        }
        [self.duibiTypeMenu setText:_contrastName];
    }else if ([_currentMenu isEqualToString:@"buttonpress2"]){
        //备注：日=1 月=2 年=3
        if ([model.title isEqualToString:@"年"]) {
            _xslxType=@"3";
        }else if ([model.title isEqualToString:@"月"]) {
            _xslxType=@"2";
        }
        [self.showTypeMenu setText:model.title];
        //更新时间
        [self changeTimeWithShowType];
    }
}

-(void)changeTimeWithShowType{
    //默认开始与结束时间
    if ([_xslxType isEqualToString:@"3"]) {
        _startTime=[CommonTool getDateTimeDifferenceWithYear:-1 Month:0 Day:0 Rule:@"yyyy"];
    }else{
        _startTime=[CommonTool getDateTimeDifferenceWithYear:0 Month:-1 Day:0 Rule:@"yyyyMM"];
    }
    [_startTimeMenu setText:_startTime];
}

-(void)onQueren:(MyUIDatePicker *)datePicker{
    //20160729（时间格式）
    NSDateFormatter *dateFormat = [ [NSDateFormatter alloc] init];
    //备注：日=1 月=2 年=3
    if ([_xslxType isEqualToString:@"3"]) {
        [dateFormat setDateFormat:@"yyyy"];
    }else if ([_xslxType isEqualToString:@"2"]) {
        [dateFormat setDateFormat:@"yyyyMM"];
    }
    NSString *newDateStr = [dateFormat stringFromDate:datePicker.datePicker.date];
    [self.startTimeMenu setText:newDateStr];
    _startTime=newDateStr;
    [_pickerOverlay removeFromSuperview];
    _is_picker_show=NO;
}

-(void)overlaycancel{
    [self onCancel:_datePicker];
}

-(void)onCancel:(MyUIDatePicker *)datePicker{
    [_pickerOverlay removeFromSuperview];
    _is_picker_show=NO;
}


-(void)startTimeClick:(id)sender{
    if (!_is_picker_show) {
        [self addSubview:_pickerOverlay];
        _is_picker_show=YES;
    }
}

-(void)onClickQuery{
    int i=0;
    if ([self.energyTypeMenu.text isEqualToString:@""]) {
        i++;
        [CommonTool showAllTextDialogWithText:@"请选择能源类型" parentView:self];
    }else{
        if ([self.duibiTypeMenu.text isEqualToString:@""]) {
            i++;
            [CommonTool showAllTextDialogWithText:@"请选择对比方式" parentView:self];
        }else{
            if ([self.showTypeMenu.text isEqualToString:@""]) {
                i++;
                [CommonTool showAllTextDialogWithText:@"请选择显示类型" parentView:self];
            }else{
                if ([self.startTimeMenu.text isEqualToString:@""]) {
                    i++;
                    [CommonTool showAllTextDialogWithText:@"请选择开始时间" parentView:self];
                }else{
                    NSDate *start;
                    NSDate *end = [NSDate date];
                    if ([_xslxType isEqualToString:@"2"]) {
                        start = [CommonTool StringToDate:self.startTimeMenu.text rule:@"yyyyMM"];
                    }else{
                        start = [CommonTool StringToDate:self.startTimeMenu.text rule:@"yyyy"];
                    }
                    
                    NSTimeInterval timeBetween = [end timeIntervalSinceDate:start];
                    if (timeBetween<0) {
                        i++;
                        [CommonTool showAllTextDialogWithText:@"选择时间大约当前时间" parentView:self];
                    }
                }
            }
            
        }
    }
    if(i==0){
        if([_delegate respondsToSelector:@selector(onQueryChartData:esCode:xslx:startTime:orgid:structType:contrastType:contrastName:)]){
            [_delegate onQueryChartData:self esCode:_energyType xslx:_xslxType startTime:_startTime orgid:_orgid structType:@"4" contrastType:_contrastType contrastName:_contrastName];
        }
    }
}

#pragma mark - 数据源方法
#pragma mark 返回分组数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//设置rowHeight
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [ShiPei CGFloatMakeScale:35];
}

#pragma mark 返回每组行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView==self.GYMeunTableView) {
        return self.conditionInfos.count;
    }else{
        return self.queryDataInfos.count;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (tableView==self.GYMeunTableView) {
        energyConditionInfo *model;
        model=[self.conditionInfos objectAtIndex:indexPath.row];
        _currentAreaName=model.condition;
        //id:name:00
        NSString *temOrgId;
        temOrgId=[@"" stringByAppendingString:model.flagNo];
        temOrgId=[temOrgId stringByAppendingString:@":"];
        temOrgId=[temOrgId stringByAppendingString:model.condition];
        temOrgId=[temOrgId stringByAppendingString:@":"];
        temOrgId=[temOrgId stringByAppendingString:@"00"];
        _orgid=temOrgId;
        if ([_orgid isEqualToString:@""]) {
            _orgid=@"520100000:4:贵阳市:00";
        }
        NSLog(@"EB_orgid=%@",_orgid);
        //执行查询
        [self onClickQuery];
    }
}

#pragma mark返回每行的单元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView==self.GYMeunTableView) {
        //1.到缓存中去取cell
        static NSString *ID=@"ID";
        //2.没有则创建cell
        areaTableRadioCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
        if (cell==nil) {
            cell=[[areaTableRadioCell
                   alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        //3.设置cell的数据
        cell.areaInfo=self.conditionInfos[indexPath.row];
        //4.返回cell
        return cell;
    }else{
        //1.到缓存中去取cell
        static NSString *ID=@"ID1";
        //2.没有则创建cell
        duibiaoTableCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
        if (cell==nil) {
            cell=[[duibiaoTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        //3.设置cell的数据
        cell.queryInfo=self.queryDataInfos[indexPath.row];
        //4.返回cell
        return cell;
    }
}


-(void)setData{
    if([_delegate respondsToSelector:@selector(onSetData:)]){
        [_delegate onSetData:self];
    }
}

-(void)multipleBarChartData:(NSArray *)legend{
    //设置图标题
    [self.chartTitle setText:_title];
    [self setMultipleBarChartData:legend];
    
    [_energyBarChart animateWithYAxisDuration:2.5];
}

-(void)initBarChartStyleAndData{
    [self setupBarChartView:_energyBarChart];
    [self setBarChartParam:_energyBarChart];
    [self setLegendStyle:_energyBarChart];
}

- (void)setupBarChartView:(BarChartView *)chartView{
    //描述
    chartView.descriptionText = @"";
    //无数据默认显示
    chartView.noDataTextDescription = @"";
    //网格背景
    chartView.drawGridBackgroundEnabled = NO;
    chartView.drawBarShadowEnabled = NO;
    chartView.dragEnabled = YES;
    [chartView setScaleEnabled:NO];
    chartView.pinchZoomEnabled = NO;
    
    chartView.leftAxis.drawZeroLineEnabled = NO;
    chartView.leftAxis.axisMinValue = 0;//设置Y轴的最小值
    chartView.leftAxis.startAtZeroEnabled = YES;//从0开始绘制
    //设置X与Y轴是否可缩放
    [chartView setScaleEnabled:NO];
    //X轴的显示位置，默认是显示在上面的
    chartView.xAxis.labelPosition = XAxisLabelPositionBottom;
}

-(void)setBarChartParam:(BarChartView *)chartView{
    ChartXAxis *xAxis = chartView.xAxis;
    xAxis.labelFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:10.f];
    
    ChartYAxis *leftAxis = chartView.leftAxis;
    leftAxis.labelFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:10.f];
    leftAxis.valueFormatter = [[NSNumberFormatter alloc] init];
    leftAxis.valueFormatter.numberStyle=NSNumberFormatterDecimalStyle;
    leftAxis.valueFormatter.maximumFractionDigits = 2;
    leftAxis.drawGridLinesEnabled = NO;
    leftAxis.spaceTop = 0.25;
    
    chartView.rightAxis.enabled = NO;
}

//设置图例样式
-(void)setLegendStyle:(BarChartView *)chartView{
    //图例在柱状图中的位置
    chartView.legend.position = ChartLegendPositionBelowChartCenter;
    //字体大小
    chartView.legend.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:11.f];
}
//:(NSArray *)len
- (void)setMultipleBarChartData:(NSArray *)legend{
    NSMutableArray *dataSets = [[NSMutableArray alloc] init];
    for (int i=0; i<[_yValsEnergyLine count]; i++) {
        BarChartDataSet *set=[[BarChartDataSet alloc] initWithYVals:[_yValsEnergyLine objectAtIndex:i] label:[CommonTool getStringFromNSArray:legend key:i]];
        [set setColor:[_barColors objectAtIndex:i]];
        [dataSets addObject:set];
    }
    BarChartData *data = [[BarChartData alloc] initWithXVals:_xValsEnergyLine dataSets:dataSets];
    data.groupSpace = 0.8;
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    //自定义数据显示格式
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [formatter setPositiveFormat:@"#0.00"];
    [data setValueFormatter:formatter];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:7.f]];
    _energyBarChart.data = data;
}


#pragma mark - ChartViewDelegate

- (void)chartValueSelected:(ChartViewBase * __nonnull)chartView entry:(ChartDataEntry * __nonnull)entry dataSetIndex:(NSInteger)dataSetIndex highlight:(ChartHighlight * __nonnull)highlight{
    NSLog(@"chartValueSelected");
}

- (void)chartValueNothingSelected:(ChartViewBase * __nonnull)chartView{
    NSLog(@"chartValueNothingSelected");
}
@end
